// SmarTest Studio - 设备页面JavaScript

import { showNotification } from './utils.js';

document.addEventListener('DOMContentLoaded', function() {
    // 初始化终端
    initTerminal();
    
    // 初始化设备交互
    initDeviceInteraction();
    
    // 初始化模态框
    initModals();
});

// 初始化终端
function initTerminal() {
    const terminalInput = document.getElementById('terminalInput');
    const terminalOutput = document.getElementById('terminalOutput');
    
    if (!terminalInput || !terminalOutput) return;
    
    // 终端输入事件
    terminalInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            const command = this.value.trim();
            if (!command) return;
            
            // 添加命令到输出
            const commandLine = document.createElement('div');
            commandLine.className = 'terminal-line';
            commandLine.innerHTML = `<span class="prompt">device:/$</span> ${command}`;
            terminalOutput.appendChild(commandLine);
            
            // 清空输入
            this.value = '';
            
            // 处理命令
            processCommand(command);
            
            // 滚动到底部
            terminalOutput.scrollTop = terminalOutput.scrollHeight;
        }
    });
    
    // 清空按钮
    const clearBtn = document.querySelector('.panel-actions .bi-trash');
    if (clearBtn) {
        clearBtn.parentElement.addEventListener('click', function() {
            // 保留初始信息
            const initialLines = Array.from(terminalOutput.querySelectorAll('.terminal-line')).slice(0, 5);
            terminalOutput.innerHTML = '';
            initialLines.forEach(line => terminalOutput.appendChild(line));
            
            // 添加新的提示符
            const promptLine = document.createElement('div');
            promptLine.className = 'terminal-line prompt';
            promptLine.textContent = 'device:/$';
            terminalOutput.appendChild(promptLine);
        });
    }
    
    // 复制按钮
    const copyBtn = document.querySelector('.panel-actions .bi-clipboard');
    if (copyBtn) {
        copyBtn.parentElement.addEventListener('click', function() {
            const text = Array.from(terminalOutput.querySelectorAll('.terminal-line'))
                .map(line => line.textContent)
                .join('\n');
            
            navigator.clipboard.writeText(text)
                .then(() => {
                    showNotification('终端内容已复制到剪贴板', 'success');
                })
                .catch(err => {
                    console.error('复制失败:', err);
                    showNotification('复制失败', 'danger');
                });
        });
    }
}

// 处理终端命令
function processCommand(command) {
    const terminalOutput = document.getElementById('terminalOutput');
    const responseLine = document.createElement('div');
    responseLine.className = 'terminal-line';
    
    // 模拟命令处理
    switch (command.toLowerCase()) {
        case 'help':
            responseLine.innerHTML = `可用命令列表：<br>
- help: 显示帮助信息<br>
- ls: 列出文件<br>
- ps: 显示进程<br>
- info: 显示设备信息<br>
- install &lt;package&gt;: 安装应用<br>
- uninstall &lt;package&gt;: 卸载应用<br>
- reboot: 重启设备<br>
- clear: 清空终端`;
            break;
            
        case 'ls':
            responseLine.innerHTML = `system/  app/  data/  sdcard/<br>
config.json  device.log`;
            break;
            
        case 'ps':
            responseLine.innerHTML = `PID   USER     CMD<br>
1     root     init<br>
324   system   system_server<br>
892   app      com.example.launcher<br>
1024  app      com.example.settings`;
            break;
            
        case 'info':
            responseLine.innerHTML = `设备型号: OpenHarmony Device<br>
系统版本: OpenHarmony 3.1<br>
API版本: 9<br>
内存: 4GB<br>
存储: 64GB<br>
分辨率: 1080x2340`;
            break;
            
        case 'reboot':
            responseLine.innerHTML = '正在重启设备...';
            setTimeout(() => {
                const rebootLine = document.createElement('div');
                rebootLine.className = 'terminal-line';
                rebootLine.textContent = '设备已重启';
                terminalOutput.appendChild(rebootLine);
                
                // 添加新的提示符
                const promptLine = document.createElement('div');
                promptLine.className = 'terminal-line prompt';
                promptLine.textContent = 'device:/$';
                terminalOutput.appendChild(promptLine);
                
                // 滚动到底部
                terminalOutput.scrollTop = terminalOutput.scrollHeight;
            }, 2000);
            break;
            
        case 'clear':
            // 清空终端
            terminalOutput.innerHTML = '';
            // 添加新的提示符
            const promptLine = document.createElement('div');
            promptLine.className = 'terminal-line prompt';
            promptLine.textContent = 'device:/$';
            terminalOutput.appendChild(promptLine);
            return; // 不需要添加响应行
            
        default:
            if (command.startsWith('install ')) {
                const packageName = command.substring(8).trim();
                if (packageName) {
                    responseLine.innerHTML = `正在安装应用: ${packageName}...<br>安装成功!`;
                } else {
                    responseLine.className = 'terminal-line error';
                    responseLine.textContent = '错误: 请指定应用包名';
                }
            } else if (command.startsWith('uninstall ')) {
                const packageName = command.substring(10).trim();
                if (packageName) {
                    responseLine.innerHTML = `正在卸载应用: ${packageName}...<br>卸载成功!`;
                } else {
                    responseLine.className = 'terminal-line error';
                    responseLine.textContent = '错误: 请指定应用包名';
                }
            } else {
                responseLine.className = 'terminal-line error';
                responseLine.textContent = `错误: 命令 '${command}' 未找到`;
            }
    }
    
    terminalOutput.appendChild(responseLine);
    
    // 添加新的提示符
    const promptLine = document.createElement('div');
    promptLine.className = 'terminal-line prompt';
    promptLine.textContent = 'device:/$';
    terminalOutput.appendChild(promptLine);
}

// 初始化设备交互
function initDeviceInteraction() {
    // 设备控制按钮
    const refreshBtn = document.querySelector('.device-screen-panel .bi-arrow-clockwise');
    if (refreshBtn) {
        refreshBtn.parentElement.addEventListener('click', function() {
            const deviceContent = document.querySelector('.device-content');
            deviceContent.style.opacity = '0.5';
            setTimeout(() => {
                deviceContent.style.opacity = '1';
                showNotification('设备屏幕已刷新', 'success');
            }, 500);
        });
    }
    
    const screenshotBtn = document.querySelector('.device-screen-panel .bi-camera');
    if (screenshotBtn) {
        screenshotBtn.parentElement.addEventListener('click', function() {
            showNotification('已保存截图', 'success');
        });
    }
    
    const recordBtn = document.querySelector('.device-screen-panel .bi-record-circle');
    if (recordBtn) {
        recordBtn.parentElement.addEventListener('click', function() {
            const btn = this;
            if (btn.classList.contains('recording')) {
                btn.classList.remove('recording');
                btn.querySelector('i').className = 'bi bi-record-circle';
                showNotification('录制已停止并保存', 'success');
            } else {
                btn.classList.add('recording');
                btn.querySelector('i').className = 'bi bi-stop-circle';
                showNotification('开始录制屏幕', 'info');
            }
        });
    }
    
    // 设备导航按钮
    const navBtns = document.querySelectorAll('.device-navigation .nav-btn');
    navBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const icon = this.querySelector('i').className;
            if (icon.includes('arrow-left')) {
                showNotification('返回上一页', 'info');
            } else if (icon.includes('house')) {
                showNotification('返回主页', 'info');
            } else if (icon.includes('list')) {
                showNotification('显示任务列表', 'info');
            }
        });
    });
    
    // 应用图标点击
    const appIcons = document.querySelectorAll('.app-icon');
    appIcons.forEach(icon => {
        icon.addEventListener('click', function() {
            const appName = this.querySelector('span').textContent;
            showNotification(`启动应用: ${appName}`, 'info');
        });
    });
}

// 初始化模态框
function initModals() {
    // 安装应用按钮
    const installBtn = document.getElementById('installBtn');
    if (installBtn) {
        installBtn.addEventListener('click', function() {
            const installModal = new bootstrap.Modal(document.getElementById('installModal'));
            installModal.show();
        });
    }
    
    // 确认安装按钮
    const confirmInstall = document.getElementById('confirmInstall');
    if (confirmInstall) {
        confirmInstall.addEventListener('click', function() {
            const fileInput = document.getElementById('appFile');
            if (fileInput && fileInput.files.length > 0) {
                const fileName = fileInput.files[0].name;
                
                // 关闭模态框
                bootstrap.Modal.getInstance(document.getElementById('installModal')).hide();
                
                // 显示安装进度
                showNotification(`正在安装: ${fileName}`, 'info');
                
                // 模拟安装过程
                setTimeout(() => {
                    showNotification(`应用 ${fileName} 安装成功`, 'success');
                    
                    // 添加终端输出
                    const terminalOutput = document.getElementById('terminalOutput');
                    if (terminalOutput) {
                        const line = document.createElement('div');
                        line.className = 'terminal-line success';
                        line.textContent = `应用 ${fileName} 安装成功`;
                        terminalOutput.appendChild(line);
                        
                        // 添加新的提示符
                        const promptLine = document.createElement('div');
                        promptLine.className = 'terminal-line prompt';
                        promptLine.textContent = 'device:/$';
                        terminalOutput.appendChild(promptLine);
                        
                        // 滚动到底部
                        terminalOutput.scrollTop = terminalOutput.scrollHeight;
                    }
                }, 2000);
            } else {
                showNotification('请选择应用文件', 'warning');
            }
        });
    }
    
    // 卸载应用按钮
    const uninstallBtn = document.getElementById('uninstallBtn');
    if (uninstallBtn) {
        uninstallBtn.addEventListener('click', function() {
            const uninstallModal = new bootstrap.Modal(document.getElementById('uninstallModal'));
            uninstallModal.show();
        });
    }
    
    // 确认卸载按钮
    const confirmUninstall = document.getElementById('confirmUninstall');
    if (confirmUninstall) {
        confirmUninstall.addEventListener('click', function() {
            const packageInput = document.getElementById('appPackage');
            if (packageInput && packageInput.value.trim()) {
                const packageName = packageInput.value.trim();
                
                // 关闭模态框
                bootstrap.Modal.getInstance(document.getElementById('uninstallModal')).hide();
                
                // 显示卸载进度
                showNotification(`正在卸载: ${packageName}`, 'info');
                
                // 模拟卸载过程
                setTimeout(() => {
                    showNotification(`应用 ${packageName} 卸载成功`, 'success');
                    
                    // 添加终端输出
                    const terminalOutput = document.getElementById('terminalOutput');
                    if (terminalOutput) {
                        const line = document.createElement('div');
                        line.className = 'terminal-line success';
                        line.textContent = `应用 ${packageName} 卸载成功`;
                        terminalOutput.appendChild(line);
                        
                        // 添加新的提示符
                        const promptLine = document.createElement('div');
                        promptLine.className = 'terminal-line prompt';
                        promptLine.textContent = 'device:/$';
                        terminalOutput.appendChild(promptLine);
                        
                        // 滚动到底部
                        terminalOutput.scrollTop = terminalOutput.scrollHeight;
                    }
                }, 1500);
            } else {
                showNotification('请输入应用包名', 'warning');
            }
        });
    }
    
    // 烧录镜像按钮
    const flashBtn = document.getElementById('flashBtn');
    if (flashBtn) {
        flashBtn.addEventListener('click', function() {
            const flashModal = new bootstrap.Modal(document.getElementById('flashModal'));
            flashModal.show();
        });
    }
    
    // 确认烧录按钮
    const confirmFlash = document.getElementById('confirmFlash');
    if (confirmFlash) {
        confirmFlash.addEventListener('click', function() {
            const fileInput = document.getElementById('imageFile');
            if (fileInput && fileInput.files.length > 0) {
                const fileName = fileInput.files[0].name;
                const wipeData = document.getElementById('wipeData').checked;
                
                // 关闭模态框
                bootstrap.Modal.getInstance(document.getElementById('flashModal')).hide();
                
                // 显示烧录进度
                showNotification(`正在烧录镜像: ${fileName}${wipeData ? ' (清除数据)' : ''}`, 'info');
                
                // 模拟烧录过程
                setTimeout(() => {
                    showNotification(`镜像 ${fileName} 烧录成功`, 'success');
                    
                    // 添加终端输出
                    const terminalOutput = document.getElementById('terminalOutput');
                    if (terminalOutput) {
                        const line = document.createElement('div');
                        line.className = 'terminal-line success';
                        line.textContent = `镜像 ${fileName} 烧录成功${wipeData ? '，数据已清除' : ''}`;
                        terminalOutput.appendChild(line);
                        
                        // 添加新的提示符
                        const promptLine = document.createElement('div');
                        promptLine.className = 'terminal-line prompt';
                        promptLine.textContent = 'device:/$';
                        terminalOutput.appendChild(promptLine);
                        
                        // 滚动到底部
                        terminalOutput.scrollTop = terminalOutput.scrollHeight;
                    }
                }, 3000);
            } else {
                showNotification('请选择镜像文件', 'warning');
            }
        });
    }
}